package com.linzm.knowledge;

/**
 * @Author zimingl
 * @Date 2023/5/7 23:01
 * @Description: TODO
 */
public class GenericTest {

    public static void main(String[] args) {
        // Human<? super Apple>可以匹配任何Apple的超类型
        Human<? super Apple> human1 = new Human<>();
        Apple apple = new Apple();
        Fruit fruit1 = new Fruit();
        BigApple bigApple1 = new BigApple();
        human1.setItem(apple); // 设置Apple及其子类型对象到Human中
        RedApple redApple = new RedApple();
        human1.setItem(redApple);
        Object fruit = human1.getItem(); // 可以读取，但需要进行类型转换

        // Human<? extends BigApple>可以匹配任何BigApple的子类型
        Human<? extends BigApple> human2 = new Human<>();
        BigApple bigApple = new BigApple();
//        human2.setItem(bigApple); // 设置BigApple及其子类型对象到Human中
//         human2.setItem(new Apple()); // 编译错误，无法添加元素到Human中
        BigApple item = human2.getItem(); // 可以读取，不需要进行类型转换
    }
}

class Fruit {
}

class Apple extends Fruit {
}

class RedApple extends Apple {
}

class BigApple extends Apple {
}

class Human<T> {
    T item;

    public void setItem(T item) {
        this.item = item;
    }

    public T getItem() {
        return item;
    }
}
